package com.zealcomm.ivcscustomer.chatroom

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import com.zealcomm.adapters.ChatMessageListAdapter
import com.zealcomm.annotations.ChatMessageType
import com.zealcomm.annotations.ChatRoleType
import com.zco.util.ExceptionUtil
import com.zco.util.LogUtil
import com.zco.base.annotations.LinkType
import com.zco.base.entity.LinkInfo
import com.zco.base.entity.SessionMessage
import com.zealcomm.commonui.base.BaseFragment2
import com.zealcomm.commonui.beans.MessageContent
import com.zealcomm.commonui.databinding.FragmentChatroomBinding
import com.zco.ivcs.customer.IvcsCustomerCallback
import com.zealcomm.ivcscustomer.R
import com.zealcomm.ivcscustomer.app.IvcsApplication
import com.zealcomm.ivcscustomer.app.IvcsApplication.Companion.sendText
import com.zealcomm.ivcscustomer.service.MainActivity
import com.zealcomm.ivcscustomer.utils.Util
import com.zealcomm.utils.bindView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class ChatRoomFragment : BaseFragment2(R.layout.fragment_chatroom) {

    private val binding: FragmentChatroomBinding by bindView()
    private var mChatMessageListAdapter: ChatMessageListAdapter? = null
    private val REQUEST_IMAGE = 1001
    private val REQUEST_FILE = 1002

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.tvTitle.text = getString(R.string.chat)
        mChatMessageListAdapter = ChatMessageListAdapter(
            ChatRoleType.CUSTOMER,
            holdingActivity as Activity,
            R.layout.chat_msg_item_time,
            (holdingActivity as MainActivity).messageContents,
            IvcsApplication.customerTokenBody?.data?.profile?.picture!!,
            IvcsApplication.customerTokenBody?.data?.userName!!
        )
        binding.rvMessage.adapter = mChatMessageListAdapter
        setOnClickListener()
    }

    private fun setOnClickListener() {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
        binding.btnSend.setOnClickListener {
            val msg = binding.etMessage.text.toString().trim { it <= ' ' }
            sendText(msg, object : IvcsCustomerCallback {
                override fun onSuccess() {
                    holdingActivity!!.runOnUiThread(Runnable {
                        (holdingActivity as MainActivity).messageContents.add(
                            MessageContent(
                                ChatRoleType.CUSTOMER,
                                SessionMessage(ChatMessageType.TEXT, msg)
                            )
                        )
                        mChatMessageListAdapter!!.notifyDataSetChanged()
                        binding.rvMessage.scrollToPosition(mChatMessageListAdapter!!.itemCount - 1)
                        binding.etMessage.setText("")
                        binding.etMessage.clearFocus()
                        binding.btnSend.isEnabled = false
                    })
                }

                override fun onFailed(code: Int, error: String) {
                    holdingActivity!!.runOnUiThread(object : Runnable {
                        override fun run() {
                            binding.btnSend.isEnabled = true
                            showToast(getString(R.string.send_msg_failed))
                        }
                    })
                }
            })
            binding.btnSend.isEnabled = false
        }
        binding.backIb.setOnClickListener {
            (holdingActivity as MainActivity).removeChat()
        }
        binding.ivFile.setOnClickListener {
            intent.addCategory(Intent.CATEGORY_OPENABLE)
            intent.type = "*/*"
            startActivityForResult(intent, REQUEST_FILE)
        }
        binding.ivImage.setOnClickListener {
            intent.addCategory(Intent.CATEGORY_OPENABLE)
            intent.type = "image/*"
            startActivityForResult(intent, REQUEST_IMAGE)
        }
        binding.etMessage.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
            override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
            override fun afterTextChanged(editable: Editable) {
                binding.btnSend.isEnabled = !TextUtils.isEmpty(binding.etMessage.text.toString())
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data != null) {
            val uri = data.data
            val path = Util.getPath(context, uri)
            val name = Util.getFileRealNameFromPath(path)
            if (requestCode == REQUEST_IMAGE) {
                IvcsApplication.ivcsCustomer!!.sendFile(
                    path,
                    null,
                    name,
                    LinkType.LINK_PIC,
                    object : IvcsCustomerCallback {
                        override fun onSuccess() {
                            holdingActivity!!.runOnUiThread {
                                (holdingActivity as MainActivity).messageContents.add(
                                    MessageContent(
                                        ChatRoleType.CUSTOMER,
                                        SessionMessage(
                                            ChatMessageType.PICTURE,
                                            LinkInfo(LinkType.LINK_PIC, name, "file://$path")
                                        )
                                    )
                                )
                                mChatMessageListAdapter!!.notifyDataSetChanged()
                                binding.rvMessage.scrollToPosition(mChatMessageListAdapter!!.itemCount - 1)
                            }
                        }

                        override fun onFailed(code: Int, error: String) {
                            showToast(error)
                        }
                    })
            } else if (requestCode == REQUEST_FILE) {
                IvcsApplication.ivcsCustomer!!.sendFile(
                    path,
                    null,
                    name,
                    LinkType.LINK_DOC,
                    object : IvcsCustomerCallback {
                        override fun onSuccess() {
                            holdingActivity!!.runOnUiThread {
                                (holdingActivity as MainActivity).messageContents.add(
                                    MessageContent(
                                        ChatRoleType.CUSTOMER,
                                        SessionMessage(
                                            ChatMessageType.TEXT, name
                                        )
                                    )
                                )
                                mChatMessageListAdapter!!.notifyDataSetChanged()
                                binding.rvMessage.scrollToPosition(mChatMessageListAdapter!!.itemCount - 1)
                            }
                        }

                        override fun onFailed(code: Int, error: String) {
                            showToast(error)
                        }
                    })
            }
        }
    }

    fun notifyListView() {
        GlobalScope.launch(Dispatchers.Main) {
            try {
                mChatMessageListAdapter!!.notifyDataSetChanged()
                binding.rvMessage.scrollToPosition(mChatMessageListAdapter!!.itemCount - 1)
            } catch (e: Exception) {
                LogUtil.e(ExceptionUtil.getExceptionTraceString(e))
            }
        }
    }
}